// pages/calculateCharge/index.js
const util = require('../../utils/util.js');
const tool = require('../../utils/tool.js');

const api = require('../../config/api.js');
const user = require('../../utils/user.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    firstCategoryVisable: false,
    secondCategoryClose: false,
    chargeId: '',
    chargeInfo: {
      isSingle: false, //单收费标准   
      treeCate: [],
    },
    //计算公式
    calculateInfo: {
      labelName: '评估值',
      lowerLimit: undefined,
      upperLimit: undefined,
      calculateItem: [],
    },


    //计算参数
    chargeParams: {
      inputNum: '',
      inputNumCh: "",
      calNum: 0, //计算标准
      calNumCh: "", //计算标准
      floNum: 100, //浮动系数
      chargeNum: 0, //收费金额
      chargeNumCh: "" //收费金额
    },

    //计算过程
    processText: "",

    cateGoryOne: {
      name: '',
      isLeaf: false,
      children: [],
      calculateInfo: {
        calculateItem: [],
      }
    },
    cateGoryTwo: {

    },
    isCollect: false,


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    if (options.chargeId) {
      this.setData({
        chargeId: options.chargeId,
      })
      this.chargeDetail();
      this.collectFunQuery();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  //计费标准
  chargeDetail() {
    try {
      let that = this;
      wx.showLoading({
        title: '...',
      })
      util.request(api.chargeDetail, {
        "chargeId": that.data.chargeId,
      }, 'GET').then(function (res) {
        wx.hideLoading();
        if (res.errno === 0) {

          let data = res.data;
          that.setData({
            chargeInfo: data,
          })
          wx.setNavigationBarTitle({
            title: data.name + data.subTitle
          })
          if (data.isSingle) {
            that.setData({
              calculateInfo: data.calculateInfo,
            })
          } else {
            let cateOne = data.treeCate[0];
            that.setData({
              cateGoryOne: cateOne,
            })
            if (cateOne.isLeaf) {
              that.setData({
                calculateInfo: cateOne.calculateInfo
              })
            } else {
              let cateTwo = cateOne.children[0];
              that.setData({
                cateGoryTwo: cateTwo,
                calculateInfo: cateTwo.calculateInfo
              })
            }
          }


          console.log(data)

        }

      }).catch(err => {
        wx.hideLoading();
      });
    } catch (err) {
      console.error(err);
    }

  },

  inputChange: function (e) {

    let inputNum = e.detail.value;
    this.data.chargeParams.inputNum = inputNum;
    this.setData({
      chargeParams: this.data.chargeParams,
    })

    this.inputChangeCul();

  },

  inputChangeFloa: function (e) {
    let floNum = e.detail.value;
    this.data.chargeParams.floNum = floNum;
    this.setData({
      chargeParams: this.data.chargeParams,
    })

    this.inputChangeCul();
  },


  /**
   * 差额定率累进计算器 - 基础分段法
   * @param {number} amount - 计费金额
   * @param {Array} rates - 费率阶梯数组，每个元素包含 [上限金额, 费率]
   * @returns {number} - 总费用
   */
  inputChangeCul() {
    let totalFee = 0;
    let previousLimit = 0;

    let processText = ""; //计算过程

    let amount = this.data.chargeParams.inputNum;
    if (this.data.chargeParams.inputNum <= 0) {
      totalFee = 0;
    } else {
      let rates = this.data.calculateInfo.calculateItem;
      for (let i = 0; i < rates.length; i++) {

        let rateType = rates[i].type; //计费率方式 0： %（百分比），1：‰（千分比），2：固定值，3区间：[100-200]

        let rateFloat = 1; //计算率
        if (rateType == 0 || rateType == 1) {
          if (rateType == 0) {
            rateFloat = rates[i].fixNum / 100
          } else {
            rateFloat = rates[i].fixNum / 1000
          }


          const [limit, rate] = [rates[i].upperLimit, rateFloat];

          // 如果金额小于当前阶梯下限，则计算剩余部分并退出循环
          if (amount <= previousLimit) break;



          // 当前阶梯的计算金额（取最小值）
          let miniNum = Math.min(amount, limit);

          //-1无限大
          if (miniNum == -1) {
            miniNum = amount;
          }



          const segmentAmount = miniNum - previousLimit;

          // 只有正数部分才计算
          if (segmentAmount > 0) {
            totalFee += segmentAmount * rate;
          }

          if (i == 0) {
            processText = "" + segmentAmount + '*' + rate;
          } else {
            processText += "+" + segmentAmount + '*' + rate;
          }

          previousLimit = limit;

          // 如果金额已达到当前阶梯上限，退出循环
          if (amount <= limit) break;
        }

      }
    }

    let chargeParams = this.data.chargeParams;

    totalFee = tool.numFix(totalFee)
    //不足多少按最低算
    let calculateInfo = this.data.calculateInfo;
    if (calculateInfo.lowerLimit) {
      if (totalFee < calculateInfo.lowerLimit) {
        totalFee = calculateInfo.lowerLimit;
      }
    }
    if (calculateInfo.upperLimit) {
      if (totalFee > calculateInfo.upperLimit) {
        totalFee = calculateInfo.upperLimit;
      }
    }


    chargeParams.calNum = totalFee;
    console.log("calNum:" + chargeParams.calNum)
    chargeParams.chargeNum = totalFee;
    if (chargeParams.floNum) {
      console.log("floNum:" + chargeParams.floNum)
      chargeParams.chargeNum = (chargeParams.floNum / 100) * chargeParams.calNum;
    }
    chargeParams.inputNumCh = tool.moneyCh(chargeParams.inputNum);
    chargeParams.calNumCh = tool.moneyCh(chargeParams.calNum);
    chargeParams.chargeNumCh = tool.moneyCh(chargeParams.chargeNum);

    processText += "=" + chargeParams.calNum + "（" + chargeParams.calNumCh + "）";
    this.setData({
      chargeParams: this.data.chargeParams,
      processText: processText,
    })

  },
  firstCategoryClose() {
    this.setData({
      firstCategoryVisable: !this.data.firstCategoryVisable,
    })
  },

  secondCategoryClose() {
    this.setData({
      secondCategoryVisable: !this.data.secondCategoryVisable,
    })
  },
  selCateGory1(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index;
    let levelItem = this.data.chargeInfo.treeCate[index];
    console.log(levelItem);
    this.setData({
      cateGoryOne: levelItem,
    })
    //叶子节点
    if (levelItem.isLeaf) {
      this.setData({
        calculateInfo: levelItem.calculateInfo,
      })
      //重新计算
      this.inputChangeCul();
    }

    this.firstCategoryClose();

  },

  selCateGory2(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index;
    let levelItem = this.data.cateGoryOne.children[index];
    console.log(levelItem);
    this.setData({
      cateGoryTwo: levelItem,
    })
    //叶子节点

    this.setData({
      calculateInfo: levelItem.calculateInfo,
    })
    //重新计算
    this.inputChangeCul();

    this.secondCategoryClose();
  },
  //收藏
  collectFun() {
    let that = this;
    wx.showLoading({
      title: '...',
    })
    util.request(api.chargeCollect, {
      "chargeId": that.data.chargeId,
    }, 'GET').then(function (res) {
      wx.hideLoading();
      if (res.errno === 0) {
        wx.hideLoading();
        console.log(res.data.isCollect)
        that.setData({
          isCollect: res.data.isCollect,
        })

      }

    }).catch(err => {
      wx.hideLoading();
    });
  },

  //收藏
  collectFunQuery() {
    let that = this;
    util.request(api.chargeCollectQuery, {
      "chargeId": that.data.chargeId,
    }, 'GET').then(function (res) {

      if (res.errno === 0) {
        wx.hideLoading();
        console.log(res.data.isCollect)
        that.setData({
          isCollect: res.data.isCollect,
        })

      }

    }).catch(err => {

    });
  },
  //复制过程
  copyFun() {
    let chargeInfo = this.data.chargeInfo ;
    let chargeParams = this.data.chargeParams ;
    let txtStr = `小程序：计费宝\n 服务项目：${chargeInfo.name}\n 评估值：${chargeParams.inputNum}（${chargeParams.inputNumCh}）\n 收费标准：${this.data.processText} \n 浮动系数：${chargeParams.floNum}%\n 收费金额：收费标准*浮动系数 = ${chargeParams.calNum} * ${chargeParams.floNum}% = ${chargeParams.chargeNum}(${chargeParams.chargeNumCh}) ` ;
    wx.setClipboardData({
      data: txtStr,
      success (res) {
        
      }
    })
  }





})